<?php

namespace app\api\model;

use constant\config;
use think\Model;

class Envelopes extends Model {
    protected $table = 'envelopes';
    
    public function CapitalList() {
        return $this->hasMany('Capital', 'envelopes_id', 'envelopes_id')->where('types', 1)->where('enable', 1)->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->field('projectId,capital_id,class_a,class_b as  projectTitle,company,square,un_Price as projectMoney,zhi,to_price as allMoney,fen as types,increment,gold_suite as type,capital.agency,acceptance,projectRemark as remarks,enable,approve,approval_reason,concat(capital.reason_for_deduction,if(capital.modified_quantity=0,"",",减量:"),if(capital.modified_quantity=0,"",round(capital.square-capital.modified_quantity,2))) as reasonForDeduction,envelopes_id,categoryName,rule as sectionTitle,capital.modified_quantity,products,up_products as isGiveUpProducts,products_square,uniqueNumber,products_id,capital.give as giveType,give_to_money,mergeTag,mergePrice,mergeCoefficient,un_Price,isMerge,capital.warranty_years as capitalWarrantyYears,warranty_reason as warrantyReason,detailed.warranty_years,detailed.groupss,detailed.warranty_text_1,detailed.warranty_text_2,products_v2_spec,is_product_choose,unique_status,products_spec_price,types as typess,increment_per_unit_volume as unitVolume,unit_volume as initialVolume,capital.artificial,capital.small_order_fee as smallOrderFee,capital.sub_discounted_money as subDiscountedMoney,capital.sub_expense_money as subExpenseMoney,if(capital.settlement_method=3 or capital.settlement_method=4,1,0) as directSales')->order('sort asc');
    }
    
    public function CapitalDatas() {
        return $this->hasMany('Capital', 'envelopes_id', 'envelopes_id')->where('types', 1)->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->field('projectId,capital_id,class_a,class_b as  projectTitle,company,square,un_Price as projectMoney,zhi,to_price as allMoney,fen as types,increment,gold_suite as type,capital.agency,acceptance,projectRemark as remarks,enable,approve,approval_reason,concat(capital.reason_for_deduction,if(capital.modified_quantity=0,"",",减量:"),if(capital.modified_quantity=0,"",round(capital.square-capital.modified_quantity,2))) as reasonForDeduction,envelopes_id,categoryName,rule as sectionTitle,capital.modified_quantity,products,up_products as isGiveUpProducts,products_square,uniqueNumber,products_id,capital.give as giveType,give_to_money,mergeTag,mergePrice,mergeCoefficient,un_Price,isMerge,capital.warranty_years as capitalWarrantyYears,warranty_reason as warrantyReason,detailed.warranty_years,detailed.groupss,detailed.warranty_text_1,detailed.warranty_text_2,products_v2_spec,is_product_choose,unique_status,products_spec_price,types as typess,increment_per_unit_volume as unitVolume,unit_volume as initialVolume,capital.artificial,capital.small_order_fee as smallOrderFee,capital.sub_discounted_money as subDiscountedMoney,capital.sub_expense_money as subExpenseMoney,if(capital.settlement_method=3 or capital.settlement_method=4,1,0) as directSales')->order('sort asc');
    }
    
    public function producCapitalList() {
        return $this->hasMany('Capital', 'envelopes_id', 'envelopes_id')->where('types', 1)->where('is_product_choose', 0)->where('products_v2_spec', '<>', 0)->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->field('projectId,capital_id,class_a,class_b as  projectTitle,company,square,un_Price as projectMoney,zhi,to_price as allMoney,fen as types,increment,gold_suite as type,capital.agency,acceptance,projectRemark as remarks,enable,approve,approval_reason,concat(capital.reason_for_deduction,if(capital.modified_quantity=0,"",",减量:"),if(capital.modified_quantity=0,"",round(capital.square-capital.modified_quantity,2))) as reasonForDeduction,envelopes_id,categoryName,rule as sectionTitle,capital.modified_quantity,products,up_products as isGiveUpProducts,products_square,uniqueNumber,products_id,capital.give as giveType,give_to_money,mergeTag,mergePrice,mergeCoefficient,un_Price,isMerge,capital.warranty_years as capitalWarrantyYears,warranty_reason as warrantyReason,detailed.warranty_years,detailed.groupss,detailed.warranty_text_1,detailed.warranty_text_2,products_v2_spec,is_product_choose,unique_status,products_spec_price,types as typess,increment_per_unit_volume as unitVolume,unit_volume as initialVolume,capital.artificial,capital.small_order_fee as smallOrderFee,capital.sub_discounted_money as subDiscountedMoney,capital.sub_expense_money as subExpenseMoney,if(capital.settlement_method=3 or capital.settlement_method=4,1,0) as directSales')->order('sort asc');
    }
    
    public function OrderList() {
        return $this->hasOne('OrderModel', 'order_id', 'ordesr_id')->field('order_id,state');
    }
    
    
    public function getFind($envelopes_id) {
        return $this->where('envelopes_id', $envelopes_id)->find();
    }
    
    /*
     * 验证
     */
    public function testAndVerify(array $companyJson, array $productJson, string $order_id, array $envelopes, $common, $capital, $detailedOptionValue, $capitalValue, $orderModel, $give_money, $purchasing_discount, $couponId, $productIds, $user_id, $capitalId = [], $envelopesProductUniqueNumber = [], $strongPrompting,$gong) {
        
        $mainMaterials   = [];//套餐中时候存在主材
        $agencyMaterials = [];//套餐中时候存在代购主材
        $productOld      = [];//老产品
        $productNew      = [];//新产品
        //套餐清单总价
        $totalPriceOfPackage = 0;
        $coutMainMoeny       = [];
        $capitalList         = [];
        $companyLists        = [];
        $productList         = [];
        $capitalListValue    = [];
        $productToMonry      = 0;
        $givePrice           = 0;
        $giveMainPrice       = 0;
        $toPrice             = 0;
        $agent_amount        = 0;
        $user_id=$user_id['user_id'];
        $couponList    = [];
        $order_setting = db('order_setting')->where('order_id', $order_id)->find();
        $order = db('order')->where('order_id', $order_id)->find();
        $specsList  = [];
        $exist      = [];
        if ($companyJson) {
            if (!empty($companyJson)) {
                foreach ($companyJson as $ke => $value) {
                    $value['NewProducts']         = 0;
                    $value['sales_method']        = 0;
                    $value['products_spec_price'] = isset($value['productsSpecPrice']) ? $value['productsSpecPrice'] : 0;
                    $companyLists[]               = $value;
                    
                    $exist[] = ['product_id' => $value['product_id'], 'projectTitle' => $value['projectTitle'], 'categoryName' => $value['categoryName'], 'fang' => $value['fang']];
                    foreach ($value['specsList'] as $m) {
                        $specsList[] = ['option_value_id' => $m['option_value_id'], 'option_value_title' => $m['option_value_title'],];
                    }
                    
                }
                
            }
        }
        if (!empty($productJson)) {
            $arrProduct1 = [];
            $arrProduct2 = [];
            foreach ($productJson as $item) {
                if (!empty($item)) {
                    $arrProduct1[] = $item['uniqueNumber'];
                }
                
            }
            if (!empty($capitalId)) {
                foreach ($capitalId as $item) {
                    if ($item['products_v2_spec'] != 0) {
                        $arrProduct2[] = $item['uniqueNumber'];
                    }
                    
                }
                $resultProduct = array_diff($arrProduct2, $arrProduct1);
                if (!empty($resultProduct)) {
                    db('capital')->where('ordesr_id', $order_id)->whereIn('uniqueNumber', $resultProduct)->where('products_v2_spec', "<>", 0)->delete();
                }
                
            }
            foreach ($productJson as $item) {
                if (!empty($item['list'])) {
                    foreach ($item['list'] as $k => $v) {
                        if (!empty($v['data'])) {
                            foreach ($v['data'] as $ke => $value) {
                                $value['categoryName']        = $v['title'];
                                $value['products_spec_price'] = $v['productsSpecPrice'];
                                $value['initialSalesVolume']  = isset($item['initialSalesVolume']) ? $item['initialSalesVolume'] : 0;
                                $value['startingVolume']      = isset($item['startingVolume']) ? $item['startingVolume'] : 0;
                                $value['sales_method']        = isset($item['sales_method']) ? $item['sales_method'] : 1;
                                $value['products_unit_price'] = isset($item['productsUnitPrice']) ? $item['productsUnitPrice'] : 0;
                                $value['NewProducts']         = 1;
                                $value['fang']                = $value['square'];
                                $value['product_id']          = $value['projectId'];
                                $value['unit']                = $value['company'];
                                $value['products']            = 1;
                                $value['type']                = 1;
                                $value['prices']              = $value['projectMoney'];
                                $value['sectionTitle']        = isset($value['sectionTitle']) ? $value['sectionTitle'] : '';
                                $productList[]                = $value;
                            }
                        }
                        
                    }
                }
                
            }
        } else {
            if (!empty($envelopesProductUniqueNumber)) {
                db('capital')->where('ordesr_id', $order_id)->whereIn('uniqueNumber', $envelopesProductUniqueNumber)->where('products_v2_spec', "<>", 0)->delete();
            }
        }
        $op         = array_merge($companyLists, $productList);
        if($order['business_type']  ==2){
            $sys_config = db('sys_config', config('database.zong'))->where('keyss', 'd_strong_associations')->value('valuess');
        }elseif($order['business_type']  ==3){
            $sys_config = db('sys_config', config('database.zong'))->where('keyss', 'x_strong_associations')->value('valuess');
        }else{
             $sys_config = db('sys_config', config('database.zong'))->where('keyss', 'strong_associations')->value('valuess');
        }
       
        $sys_config = json_decode($sys_config, true);
        if (!empty($op)) {
            if (!empty($capitalId)) {
                $arr1   = array_column($capitalId, 'capital_id');
                $arr2   = array_column($op, 'capital_id');
                $result = array_diff($arr1, $arr2);
                if (!empty($result)) {
                    db('capital')->whereIn('capital_id', $result)->where('products_v2_spec', 0)->delete();
                }
            }
            $mergeArray = [];//合并
            foreach ($op as $k => $l) {
                $op[$k]['newFang'] = 0;
                if ($l['isMerge']) {
                    $pf = json_decode(explode('|', $l['mergeTag'])[1], true);
                    sort($pf);
                    $l['mergeTag']      = explode('|', $l['mergeTag'])[0] . '|' . json_encode($pf);
                    $mergeArray[]       = $l;
                    $op[$k]['mergeTag'] = $l['mergeTag'];
                }
                
                
            }
            foreach ($exist as $o) {
                foreach ($sys_config as $value) {
                    if ($o['product_id'] == $value['id'] && $value['type'] == 1) {
                        foreach ($value['select'] as $k1 => $l) {
                            if (!in_array($l['id'], array_column($exist, 'product_id'))) {
                                return ['code' => 301, 'id' => $l['id'], 'is_required' => 1, 'title' => $o['projectTitle'], 'msg' => $o['projectTitle'] . '有强关联请添加', 'list' => $op];
                            }
                        }
                        
                    }
                    
                    if ($strongPrompting != 1) {
                        if ($o['product_id'] == $value['id'] && $value['type'] == 2) {
                            foreach ($value['select'] as $k1 => $l) {
                                if (($value['space'] == '' || (in_array($o['categoryName'], explode(",", $value['space'])) && (isset($value['release']) && $value['release'] <= $o['fang']))) && !in_array($l['id'], array_column($exist, 'product_id'))) {
                                    return ['code' => 301, 'id' => $l['id'], 'is_required' => 2, 'title' => $o['projectTitle'], 'msg' => $o['projectTitle'] . '有强提示请确认添加', 'list' => $op];
                                }
                            }
                            
                        }
                        if ($o['product_id'] == $value['id'] && $value['type'] == 3) {
                            foreach ($specsList as $lk) {
                                foreach ($value['select'] as $l) {
                                    if ($lk['option_value_id'] == $l['id'] && !in_array($value['ids'], array_column($exist, 'product_id'))) {
                                        return ['code' => 301, 'id' => $l['id'], 'is_required' => 3, 'title' => $o['projectTitle'], 'msg' => $o['projectTitle'] . '请关联添加清单' . $value['idstitle'] . '该清单的当前规格', 'list' => $op];
                                    }
                                }
                            }
                            
                        }
                    }
                    
                    
                    if ($o['product_id'] == $value['id'] && $value['type'] == 4) {
                        foreach ($specsList as $lk) {
                            foreach ($value['select'] as $l) {
                                if ($lk['option_value_id'] == $l['id'] && in_array($value['selectsid'], array_column($specsList, 'option_value_id'))) {
                                    return ['code' => 301, 'id' => $l['id'], 'is_required' => 4, 'title' => $o['projectTitle'], 'msg' => '系统校验到清单' . $o['projectTitle'] . '中的规格' . $value['selectstitle'] . '重复添加，其中“西卡JS防水2遍”中已包含“渗透结晶界面工艺”，请查重后再提交。', 'list' => $op];
                                }
                            }
                        }
                        
                    }
                }
                
            }
            if (!empty($mergeArray)) {
                $result = array_reduce($mergeArray, function ($temp, $item) {
                    isset($temp[$item['mergeTag']]) ? $temp[$item['mergeTag']]['fang'] += $item['fang'] : $temp[$item['mergeTag']] = $item;
                    return $temp;
                }, []);
                foreach ($result as $l) {
                    foreach ($op as $k => $pl) {
                        if ($pl['isMerge'] && ($l['mergeTag'] == $pl['mergeTag'])) {
                            $op[$k]['newFang'] = $l['fang'];
                        }
                    }
                }
            }

            //直售价格
             $zhuZhiSho    = 0;
             $daiZhiSho    = 0;
             $zhuZhiShoChan=0;
             $daiZhiShoChan=0;
            foreach ($op as $ke => $v) {
               $ValueList              = $v['specsList'];
                $v['smallOrderFeeType'] = isset($v['smallOrderFeeType']) ? $v['smallOrderFeeType'] : 0;
                if ($v['types'] == 4) {
                    $ValueId      = array_column($ValueList, 'option_value_id');
                    $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $v['product_id'], array_merge(array_unique($ValueId)),$v['fang']);
                    
                    if (!$CapitalPrice['code']) {
                        return ['code' => 300, 'msg' => $CapitalPrice['msg']];
                    }
                    if ((($CapitalPrice['data']['group']==4 && $order['business_type']  !=2) || ($CapitalPrice['data']['group']==5 && $order['business_type']  !=3)) &&  $v['agency'] == 0) {
                        return ['code' => 300, 'msg' => '【"'.$v['projectTitle'].'"】为失效清单，无法提交报价，请删除后重试'];
                    }
                    if ($v['isMerge'] && $v['newFang'] != 0) {
                        $fang = $v['newFang'];
                    } else {
                        $fang = $v['fang'];
                    }
                    $settlement_method=empty($CapitalPrice['data']['salesCommission'])?1:$CapitalPrice['data']['salesCommission'][0]['settlement_method'];
                    if(count($op)==1 && ($settlement_method==3|| $settlement_method==4) && ($give_money !=0 || $purchasing_discount !=0)){
                        return ['code' => 300, 'msg' => "根据公司销售政策，直售清单（店长固定提点清单）无法优惠，请勿设置优惠"];
                    }
                    $fangs                      = -1;
                    $small_order_fee_square_min = 0;
                    $small_order_fee_square_max = 0;
                    //小单费
                    if (!empty($CapitalPrice['data']['small_order_fee']) && ($v['products'] == 0 || ($v['products'] == 1 && $v['required'] == 2 && $v['isProductChoose'])) && $v['smallOrderFeeType'] == 1) {
                        $fangs              = $fang;
                        $smallOrderFeePrice = 0;
                        foreach ($CapitalPrice['data']['small_order_fee'] as $k => $value) {
                            if ($value['start'] <= $fang && $value['end'] > $fang) {
                                $smallOrderFeePrice         = $value['value'];
                                $small_order_fee_square_min = $value['start'];
                                $small_order_fee_square_max = $value['end'];
                            }
                        }
                        
                    }
                    $v['unique_status']               = 0;
                    $CapitalPriceSection              = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $fang, $v['unit'], $CapitalPrice['data']['small_order_fee'], $fangs);
                    $capitalMap['labor_cost_price']   = $CapitalPriceSection[0];
                    $capitalMap['sumMast']            = $CapitalPriceSection[2];
                    $capitalMap['smallOrderFeePrice'] = $CapitalPriceSection[5];
                    
                    if ($capitalMap['smallOrderFeePrice'] == 0) {
                        $small_order_fee_square_min = 0;
                        $small_order_fee_square_max = 0;
                    }
                    $capitalMap['base_cost'] = 0;
                    if ($v['agency'] == 1) {
                        $capitalMap['labor_cost_price'] = $CapitalPrice['data']['sumMast'] * $fang;
                        $capitalMap['base_cost']        = $CapitalPrice['data']['base_cost'];
                        $capitalMap['sumMast']          = $CapitalPrice['data']['sumMast'];
                    }
                    $capitalMap['toPrice']           = $CapitalPriceSection[3] * $v['fang'];
                    $capitalMap['sum']               = $CapitalPriceSection[3];
                    $capitalMap['artificial']                = $CapitalPrice['data']['sum'];
                    if($v['agency'] == 1 && $CapitalPrice['data']['userId'] !=0){
                        $capitalMap['toPrice']           =$v['allMoney'];
                        $capitalMap['labor_cost_price'] =0;
                        $capitalMap['base_cost']        = 0;
                        $capitalMap['sumMast']          = 0;
                        $capitalMap['sum']          = $v['prices'];
                        $capitalMap['artificial'] = $v['prices'];
                    }
                    $capitalMap['mast_rule']         = $CapitalPriceSection[4];
                    $capitalMap['is_product_choose'] = 1;
                    if (isset($v['products']) && $v['products'] == 1 && $v['NewProducts'] == 0) {
                        $v['unique_status']    = 0;
                        $capitalMap['toPrice'] = $v['allMoney'];
                        $totalPriceOfPackage   += $capitalMap['toPrice'];
                        $productOld[]          = ['toPrice' => $capitalMap['toPrice'], 'agency' => $v['agency'], 'sales_method' => $v['sales_method'], 'products_id' => $v['products_id'], 'schemeIds' => $v['schemeIds'], 'uniqueNumber' => $v['uniqueNumber'], 'isGiveUpProducts' => $v['isGiveUpProducts'], 'productType' => 1,];
                        $capitalMap['sum']     = $v['prices'];
                        if ($v['agency'] == 0) {
                            $mainMaterials[] = $v;
                        }
                        if ($v['agency'] == 1) {
                            $agencyMaterials[] = $v;
                        }
                        $plan_id = db('scheme_project', config('database.zong'))->Join('scheme_master', 'scheme_master.plan_id=scheme_project.plan_id', 'left')->where('scheme_project.plan_id', $v['schemeIds'])->select();
                        foreach ($plan_id as $item) {
                            if ($item['settlement_method'] == 2 && $item['projectId'] == $v['product_id']) {
                                $capitalMap['labor_cost_price'] = $item['fixed_price'];
                                $capitalMap['sumMast']          = round($item['fixed_price'] / $v['fang'], 2);
                            }
                            
                        }
                        
                        $capitalMap['mast_rule'] = '';
                    } elseif (isset($v['products']) && $v['products'] == 1 && $v['NewProducts'] == 1) {
                        if ($v['required'] == 1) {
                            $v['unique_status']    = 1;
                            $capitalMap['toPrice'] = $v['allMoney'];
                            $totalPriceOfPackage   += $capitalMap['toPrice'];
                            if ($v['agency'] == 0) {
                                $mainMaterials[] = $v;
                            }
                            if ($v['agency'] == 1) {
                                $agencyMaterials[] = $v;
                            }
                            $capitalMap['sum']       = $v['projectMoney'];
                            $capitalMap['mast_rule'] = '';
                            $productNew []           = ['toPrice' => $capitalMap['toPrice'], 'agency' => $v['agency'], 'products_id' => $v['products_id'], 'schemeIds' => $v['schemeIds'], 'sales_method' => $v['sales_method'], 'uniqueNumber' => $v['uniqueNumber'], 'sales_volume' => $v['initialSalesVolume'], 'startingVolume' => $v['startingVolume'], 'products_unit_price' => $v['products_unit_price'], 'isGiveUpProducts' => 0, 'productType' => 2,];
                        }
                        if ($v['required'] == 2 && $v['isProductChoose']) {
                            $v['unique_status'] = 0;
                            if ($v['agency'] == 1 && $v['giveType'] == 0) {
                                $agent_amount += $capitalMap['toPrice'];
                            } elseif ($v['agency'] == 0 && $v['giveType'] == 0) {
                                $toPrice += $capitalMap['toPrice'];
                            }
                            
                        }
                        if ($v['required'] == 2 && !$v['isProductChoose']) {
                            $v['unique_status']              = 0;
                            $capitalMap['is_product_choose'] = 0;
                        }
                    }
                    if ($v['giveType'] == 2 && $capitalMap['is_product_choose'] == 1) {
                        if ($v['agency'] == 1) {
                            $givePrice += $capitalMap['toPrice'] + $capitalMap['smallOrderFeePrice'];
                        } else {
                            $giveMainPrice += $capitalMap['toPrice'];
                        }
                    }
                    if ($v['agency'] == 0 && $v['products'] == 0 && $v['giveType'] == 0) {
                        $toPrice += round($capitalMap['toPrice'], 2)+ $capitalMap['smallOrderFeePrice'];
                    }
                    if ($v['agency'] == 1 && $v['products'] == 0 && $v['giveType'] == 0) {
                      
                        $agent_amount += round($capitalMap['toPrice'], 2)+ $capitalMap['smallOrderFeePrice'];
                    }
                }
                
                if (empty($envelopes)) {
                    $enable = 1;
                    if ($capitalMap['is_product_choose'] == 0) {
                        $enable = 0;
                    }
                    $v['capital_id'] = 0;
                } else {
                    $enable = 1;
                    if ($envelopes['type'] != 1) {
                        $enable = 0;
                    }
                    if ($capitalMap['is_product_choose'] == 0) {
                        $enable = 0;
                    }
                }
                if ($v['isWarranty'] == 1) {
                    $capitalList[$ke]['warrantYears']  = $CapitalPrice['data']['warrantYears'];
                    $capitalList[$ke]['warrantyText1'] = time();
                    $capitalList[$ke]['exoneration']   = strtotime(date("Y-m-d", strtotime("+" . ($CapitalPrice['data']['warrantYears'] * 12) . " months")));;
                    $capitalList[$ke]['zhi']            = 1;
                    $capitalList[$ke]['warrantyReason'] = '';
                } else {
                    $capitalList[$ke]['warrantYears']   = 0;
                    $capitalList[$ke]['zhi']            = 0;
                    $capitalList[$ke]['warrantyReason'] = isset($v['warrantyReason']) ? $v['warrantyReason'] : '';
                }
                $capitalList[$ke]['increment_per_unit_volume'] = isset($v['unitVolume']) ? $v['unitVolume'] : 0;
                $capitalList[$ke]['products_v2_spec']          = isset($v['schemeIds']) ? $v['schemeIds'] : 0;
                $capitalList[$ke]['projectTitle']              = $v['projectTitle'];
                $capitalList[$ke]['categoryTitle']             = $CapitalPrice['data']['categoryTitle'];
                $capitalList[$ke]['labor_cost_material']             = $CapitalPrice['data']['labor_cost_material'];
                $capitalList[$ke]['fang']                      = $v['fang'];
                $capitalList[$ke]['artificial']                = $capitalMap['artificial'];
                $capitalList[$ke]['sum']                       = $capitalMap['sum'];
                $capitalList[$ke]['mast_rule']                 = $capitalMap['mast_rule'];
                $capitalList[$ke]['base_cost']                 = $capitalMap['base_cost'];
                $capitalList[$ke]['sectionTitle']              = $v['sectionTitle'];
                $capitalList[$ke]['giveType']                  = $v['giveType'];
                $capitalList[$ke]['product_id']                = $v['product_id'];
                if ($v['capital_id'] != 0) {
                    $capitalList[$ke]['capital_id'] = $v['capital_id'];
                    
                } else {
                    $capitalList[$ke]['crtime']    = time();
                    $capitalList[$ke]['unit']      = $v['unit'];
                    $capitalList[$ke]['types']     = $v['types'];
                    $capitalList[$ke]['order_id']  = $order_id;
                    $capitalList[$ke]['programme'] = 1;
                    $capitalList[$ke]['type']      = $v['type'];
                }
                 $capitalList[$ke]['groupss']          = $CapitalPrice['data']['group'];
                 $capitalList[$ke]['base_contract_price'] = $CapitalPrice['data']['base_contract_price'];
                $capitalList[$ke]['toPrice']                    = $capitalMap['toPrice'] + $capitalMap['smallOrderFeePrice'];
                $capitalList[$ke]['labor_cost_price']           = $capitalMap['labor_cost_price'];
                $capitalList[$ke]['small_order_fee_square_min'] = $small_order_fee_square_min;
                $capitalList[$ke]['small_order_fee_square_max'] = $small_order_fee_square_max;
                $capitalList[$ke]['unit_volume']                = isset($v['initialVolume']) ? $v['initialVolume'] : 0;
                $capitalList[$ke]['unique_status']              = $v['unique_status'];
                $capitalList[$ke]['sumMast']                    = $capitalMap['sumMast'];
                $capitalList[$ke]['enable']                     = $enable;
                $capitalList[$ke]['categoryName']               = $v['categoryName'];
                $capitalList[$ke]['agency']                     = $v['agency'];
                $capitalList[$ke]['remarks']                    = $v['remarks'];
                $capitalList[$ke]['products_spec_price']        = 0;
                if ($v['sales_method'] != 2) {
                    $capitalList[$ke]['products_spec_price'] = isset($v['products_spec_price']) ? $v['products_spec_price'] : 0;
                }
                if ($v['agency'] == 0) {
                  if ( ($settlement_method==3|| $settlement_method==4) && $v['products'] == 0) {
                        $zhuZhiSho += $capitalList[$ke]['toPrice'];
                    }
                    if ( ($settlement_method==3|| $settlement_method==4) && $v['products'] != 0) {
                        $zhuZhiShoChan += $capitalList[$ke]['toPrice'];
                    }
                }
                if ($v['agency'] == 1) {
                   if ( ($settlement_method==3|| $settlement_method==4) && $v['products'] == 0) { 
                        $daiZhiSho +=$capitalList[$ke]['toPrice'];
                    }
                    if ( ($settlement_method==3|| $settlement_method==4) && $v['products'] != 0) {
                       
                        $daiZhiShoChan += $capitalList[$ke]['toPrice'];
                    }
                }
                $capitalList[$ke]['is_product_choose'] = $capitalMap['is_product_choose'];
                $capitalList[$ke]['settlement_method'] = $settlement_method;
                $capitalList[$ke]['fixed_rate'] =  empty($CapitalPrice['data']['salesCommission'])?0:$CapitalPrice['data']['salesCommission'][0]['fixed_rate'];
                $capitalList[$ke]['fixed_cost'] =  empty($CapitalPrice['data']['salesCommission'])?0:$CapitalPrice['data']['salesCommission'][0]['fixed_cost'];
                $capitalList[$ke]['small_order_fee']   = $capitalMap['smallOrderFeePrice'];
                $capitalList[$ke]['envelopes_id']      = empty($envelopes) ? 0 : $envelopes['envelopes_id'];
                $capitalList[$ke]['products']          = isset($v['products']) ? $v['products'] : 0;
                $capitalList[$ke]['up_products']       = isset($v['isGiveUpProducts']) ? $v['isGiveUpProducts'] : 0;
                $capitalList[$ke]['products_square']   = isset($v['products_square']) ? $v['products_square'] : 0;
                $capitalList[$ke]['products_id']       = isset($v['products_id']) ? $v['products_id'] : 0;
                $capitalList[$ke]['give_to_money']     = isset($v['give_to_money']) ? $v['give_to_money'] : 0;
                $capitalList[$ke]['uniqueNumber']      = isset($v['uniqueNumber']) ? $v['uniqueNumber'] : 0;//三
                $capitalList[$ke]['mergeTag']          = isset($v['mergeTag']) ? $v['mergeTag'] : 0;//三
                $capitalList[$ke]['prices']            = isset($v['prices']) ? $v['prices'] : 0;//三
                $capitalList[$ke]['mergeCoefficient']  = isset($v['mergeCoefficient']) ? $v['mergeCoefficient'] : 0;//三
                $capitalList[$ke]['isMerge']           = isset($v['isMerge']) ? $v['isMerge'] : 0;//三
                
                foreach ($v['specsList'] as $item) {
                    $capitalList[$ke]['specsList'][] = ['capital_id' => $v['capital_id'],//单位
                        'option_value_title' => $item['option_value_title'],//方量
                        'option_value_id' => $item['option_value_id'],//单价
                        'condition' => $item['condition'],//规则
                        'price' => $item['price'],//规则
                        'artificial' => $item['artificial'],//规则
                    ];
                }
                
            }
            
        }
        //套餐
        $result = array();
        if (!empty($productIds)) {
            if (!empty($productOld) && !empty($productNew)) {
                $coutMainMoeny = array_merge($productOld, $productNew);
            } elseif (!empty($productOld) && empty($productNew)) {
                $coutMainMoeny = $productOld;
            } elseif (empty($productOld) && !empty($productNew)) {
                $coutMainMoeny = $productNew;
            }
            
            if (!empty($coutMainMoeny)) {
                $title = array_unique(array_column($coutMainMoeny, 'uniqueNumber'));
                foreach ($title as $key => $info) {
                    $money    = 0;
                    $allMoney = [];
                    foreach ($coutMainMoeny as $item) {
                        if ($info == $item['uniqueNumber']) {
                            $result[$key]['products_id']         = $item['products_id'];
                            $result[$key]['schemeIds']           = $item['schemeIds'];
                            $result[$key]['sales_method']        = $item['sales_method'];
                            $result[$key]['sales_volume']        = isset($item['sales_volume']) ? $item['sales_volume'] : 0;
                            $result[$key]['startingVolume']      = isset($item['startingVolume']) ? $item['startingVolume'] : 0;
                            $result[$key]['products_unit_price'] = isset($item['products_unit_price']) ? $item['products_unit_price'] : 0;
                            $result[$key]['productType']         = $item['productType'];
                            $money                               += $item['toPrice'];
                            $allMoney[]                          = ['toPrice' => $item['toPrice'], 'agency' => $item['agency'], 'isGiveUpProducts' => $item['isGiveUpProducts'],];
                        }
                    }
                    if ($result[$key]['productType'] == 1) {
                        $products_spec                       = db('products_spec', config('database.zong'))->where('products_id', $result[$key]['products_id'])->join('products', 'products.id=products_spec.products_id', 'left')->join('unit', 'products.products_unit=unit.id', 'left')->where('scheme_id', $result[$key]['schemeIds'])->field('products_spec.*,products.*,unit.title as unitTitle')->find();
                        $productToMonry                      += round($products_spec['products_spec_price'] / 100, 2);
                        $beLeftOver                          = round($money, 2) - round($products_spec['products_spec_price'] / 100, 2);
                        $result[$key]['products_spec_price'] = round($products_spec['products_spec_price'] / 100, 2);
                        $title                               = $products_spec['products_title'] . '-' . $products_spec['products_spec_title'];
                        $products_spec_price                 = round($products_spec['products_spec_price'] / 100, 2);
                        $products_spec_title                 = $products_spec['products_spec_title'];
                        $products_unit                       = $products_spec['unitTitle'];
                    } elseif ($result[$key]['productType'] == 2) {
                        $products_spec = db('products_v2_spec', config('database.zong'))->field('products.*,products_v2_spec.*,products.id as ids,unit.title as unitTitle,products.sales_method,products.products_unit_price')->join('products_v2 products', 'products.id=products_v2_spec.products_id', 'left')->join('unit', 'products.products_unit=unit.id', 'left')->where('products_v2_spec.products_id', $result[$key]['products_id'])->where('products_v2_spec.is_required_module', 1)->select();
                        $products_spec_priceSum=0;
                        foreach ($products_spec as $lp) {
                            if ($lp['sales_method'] == 2) {
                                $productToMonry                      += round($lp['products_unit_price'] * $result[$key]['sales_volume'], 2);
                                $products_spec_price                 = round($lp['products_unit_price'] * $result[$key]['sales_volume'], 2);
                                $products_spec_priceSum +=$products_spec_price;
                                $result[$key]['products_unit_price'] = $lp['products_unit_price'];
                            } else {
                                $productToMonry      += round($lp['products_spec_price'], 2);
                                $products_spec_price = round($lp['products_spec_price'], 2);
                                $products_spec_priceSum +=$products_spec_price;
                            }
                        }
                        $products_spec_price=$products_spec_priceSum;
                        // $products_spec_price = round(array_sum(array_column($products_spec, 'products_spec_price')), 2);
                        $beLeftOver          = round($money - $products_spec_priceSum, 2);
                        $title               = $products_spec[0]['products_title'];
                        $products_spec_title = "";
                        $products_unit       = $products_spec[0]['unitTitle'];
                    };
                    $coutMainMoenyDiscountMoney  = 0;
                    $coutMoenyDiscountMoney      = 0;
                    $products_main_expense       = 0;
                    $products_purchasing_expense = 0;
                    if ($beLeftOver >= 0) {
                        $last_man_datas = array_column($allMoney, 'toPrice');
                        array_multisort($last_man_datas, SORT_ASC, $allMoney);
                        $Proportion = 0;
                        foreach ($allMoney as $k => $m) {
                            if ($k != count($allMoney) - 1) {
//                                $Proportion                 += bcdiv($m['toPrice'], $money, 2);
                                $allMoney[$k]['proportion'] = bcdiv($m['toPrice'], $money, 2);
                            }
                            if ($m['agency'] == 1 && $m['isGiveUpProducts'] == 0) {
                                $products_purchasing_expense += $m['toPrice'];
                            }
                            if ($m['agency'] == 0 && $m['isGiveUpProducts'] == 0) {
                                $products_main_expense += $m['toPrice'];
                            }
                            
                        }
                        foreach ($allMoney as $k => $m) {
                            if ($k == count($allMoney) - 1) {
                                $allMoney[$k]['proportionAmount'] = bcsub($beLeftOver, $Proportion, 3);
                            } else {
                                $allMoney[$k]['proportionAmount'] = bcmul($beLeftOver, $m['proportion'], 2);
                                $Proportion                       += $allMoney[$k]['proportionAmount'];
                            }
                            
                        }
                        foreach ($allMoney as $k => $j) {
                            if ($j['agency'] == 1) {
                                $coutMoenyDiscountMoney += $j['proportionAmount'];
                            }
                            if ($j['agency'] == 0) {
                                $coutMainMoenyDiscountMoney += $j['proportionAmount'];
                            }
                        }
                    } else {
                        return ['code' => 300, 'msg' => "产品配置出现问题，请截图联系供应链【西蒙】【产品" . $result[$key]['products_id'] . "】"];
                    }
                    $result[$key]['money']      = $money;
                    $result[$key]['beLeftOver'] = $beLeftOver;
//                    $result[$key]['startingVolume']                  = $result[$key]['startingVolume'] ;
                    $result[$key]['coutMainMoenyDiscount']       = $coutMainMoenyDiscountMoney;
                    $result[$key]['coutMoenyDiscount']           = $coutMoenyDiscountMoney;
                    $result[$key]['products_main_expense']       = round(($products_main_expense * $order_setting['max_expense_rate']) / 100, 2);
                    $result[$key]['products_purchasing_expense'] = round(($products_purchasing_expense * $order_setting['max_agent_expense_rate']) / 100, 2);
                    $result[$key]['uniqueNumber']                = $info;
                    $result[$key]['title']                       = $title;
                    $result[$key]['products_spec_price']         = $products_spec_price;
                    $result[$key]['products_spec_title']         = $products_spec_title;
                    $result[$key]['products_unit']               = $products_unit;
                }
                
                $result = array_values($result);
                
            }
            
        }
        $coutMoenyDiscountMoney     = 0;
        $coutMainMoenyDiscountMoney = 0;
        $resultListArray            = [];
        $scheme_useListArray        = [];
        $manProductToMonry          = 0;
        $agentProductToMonry        = 0;
        if (!empty($result)) {
            if (!empty(array_column($result, 'coutMainMoenyDiscount'))) {
                $coutMainMoenyDiscountMoney += array_sum(array_column($result, 'coutMainMoenyDiscount'));
            }
            if (!empty(array_column($result, 'coutMoenyDiscount'))) {
                $coutMoenyDiscountMoney += array_sum(array_column($result, 'coutMoenyDiscount'));
                
            }
            foreach ($result as $k => $o) {
                $resultListArray[$k]['products_main_discount_money']       = $o['coutMainMoenyDiscount'];
                $resultListArray[$k]['products_purchasing_discount_money'] = $o['coutMoenyDiscount'];
                $resultListArray[$k]['money']                              = $o['money'];
                $resultListArray[$k]['beLeftOver']                         = $o['beLeftOver'];
                $resultListArray[$k]['uniqueNumber']                       = $o['uniqueNumber'];
                $resultListArray[$k]['products_id']                        = $o['products_id'];
                $resultListArray[$k]['envelopes_id']                       = empty($envelopes) ? 0 : $envelopes['envelopes_id'];
                $resultListArray[$k]['crtime']                             = time();
                $resultListArray[$k]['products_spec_price']                = $o['products_spec_price'];
                $resultListArray[$k]['schemeIds']                          = $o['schemeIds'];
                $resultListArray[$k]['title']                              = $o['title'];
                $resultListArray[$k]['products_spec_title']                = $o['products_spec_title'];
                $resultListArray[$k]['products_unit']                      = $o['products_unit'];
                $resultListArray[$k]['products_spec_title']                = $o['products_spec_title'];
                $resultListArray[$k]['products_unit']                      = $o['products_unit'];
                $resultListArray[$k]['products_main_expense']              = $o['products_main_expense'];
                $resultListArray[$k]['products_purchasing_expense']        = $o['products_purchasing_expense'];
                $resultListArray[$k]['initial_sales_volume']               = $o['startingVolume'];
                $resultListArray[$k]['sales_volume']                       = $o['sales_volume'];
                $resultListArray[$k]['sales_method']                       = $o['sales_method'];
                $resultListArray[$k]['products_unit_price']                = $o['products_unit_price'];
                $resultListArray[$k]['products_type']                      = $o['productType'];
                $scheme_useListArray[$k]['plan_id']                        = $o['products_id'];
                $scheme_useListArray[$k]['user_id']                        = $user_id;
                $scheme_useListArray[$k]['creation_time']                  = time();
                $scheme_useListArray[$k]['city']                           = config('cityId');
                $scheme_useListArray[$k]['order_id']                       = $order_id;
                $scheme_useListArray[$k]['envelopes_id']                   = empty($envelopes) ? 0 : $envelopes['envelopes_id'];
                $scheme_useListArray[$k]['type']                           = 3;
                if ($o['products_main_expense'] != 0) {
                    $manProductToMonry += $o['products_spec_price'];
                }
                if ($o['products_main_expense'] == 0) {
                    $agentProductToMonry += $o['products_spec_price'];
                }
            }
            
        }
        //优惠券
        if (!empty($couponId) && trim($couponId) != 'null') {
            $exp       = new \think\db\Expression('field(coupon.coupon_type,1,2)');
            $couponId  = json_decode($couponId, true);
            $couponId  = implode(array_column($couponId, 'id'), ',');
            $coupon    = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->whereIn('coupon_user.id', $couponId)->order($exp)->select();
            $fullMinus = [];
            $discount  = [];
            foreach ($coupon as $item) {
                if ($item['coupon_type'] == 1) {
                    $fullMinus[] = $item;
                }
                if ($item['coupon_type'] == 2) {
                    $discount[] = $item;
                }
            }
            $coupon_use_type = array_column($fullMinus, 'coupon_use_type');
            array_multisort($coupon_use_type, SORT_ASC, $fullMinus);
            $discountcoupon_use_type = array_column($discount, 'coupon_use_type');
            array_multisort($discountcoupon_use_type, SORT_ASC, $discount);
            $coupon           = array_merge($fullMinus, $discount);
            $ManFullMinusList = 0;
            $PrFullMinusList  = 0;
            foreach ($coupon as $k => $list) {
                $coupon_amount             = 0;
                $purchasing_id             = 0;
                $purchasing_discount_money = 0;
                $main_id                   = 0;
                if ($list['coupon_use_type'] == 1) {
                    if ((isset($toPrice) && $toPrice != 0) || $manProductToMonry != 0) {
                         $o = bcsub($toPrice,$zhuZhiSho,2);
                        if ($manProductToMonry > 0) {
                            $o += bcsub($manProductToMonry,$zhuZhiShoChan,2);
                        }
                        if ($agentProductToMonry == 0) {
                           $o = bcsub($o,$daiZhiShoChan,2);
                        }
                      
                        if ($o < ($list['coupon_limit'] / 100)) {
                            return ['code' => 300, 'msg' => "未达到使用门槛"];
                        }
                        if ($list['coupon_type'] == 1) {
                            $coupon_amount    = ($list['coupon_amount'] / 100);
                            $ManFullMinusList = $o - $coupon_amount - $give_money;
                        } elseif ($list['coupon_type'] == 2) {
                            if ($ManFullMinusList == 0) {
                                $ManFullMinusList = $o - $give_money;
                            }
                            $coupon_amount    = $ManFullMinusList * (1 - ($list['coupon_discount'] / 100));
                            $ManFullMinusList = $o - $coupon_amount - $give_money;
                        }
                        $main_id = $list['id'];
                    }
                }
                if ($list['coupon_use_type'] == 3) {
                    if ((isset($agent_amount) && $agent_amount != 0) && (isset($toPrice) && $toPrice != 0)) {
                        $o1 = bcsub($agent_amount,$daiZhiSho, 2);
                        $o  = bcsub($toPrice,$zhuZhiSho, 2);
                        if ($list['coupon_type'] == 1) {
                            $coupon_amount             = ($list['coupon_amount'] / 100);
                            $purchasing_discount_money = ($list['coupon_amount'] / 100);
                        } elseif ($list['coupon_type'] == 2) {
                            if ($ManFullMinusList == 0) {
                                $ManFullMinusList = $o - $give_money;
                            }
                            if ($PrFullMinusList == 0) {
                                $PrFullMinusList = $o1;
                            }
                            $coupon_amount             = $ManFullMinusList * (1 - ($list['coupon_discount'] / 100));
                            $purchasing_discount_money = $PrFullMinusList * (1 - ($list['coupon_discount'] / 100));
                        }
                        if ($list['coupon_type'] == 1) {
                            if ($o < $coupon_amount * 0.5 && $o1 < $purchasing_discount_money * 0.5) {
                                return ['code' => 300, 'msg' => "未达到使用门槛"];
                            } elseif ($o > $coupon_amount * 0.5 && $o1 < $purchasing_discount_money * 0.5) {
                                
                                $many = $purchasing_discount_money * 0.5 - $o1;
                                if ($o < $coupon_amount * 0.5 + $many) {
                                    return ['code' => 300, 'msg' => "未达到使用门槛"];
                                }
                                $coupon_amount             = $coupon_amount + $many;
                                $purchasing_discount_money = $o1;
                                $ManFullMinusList          = $o - $coupon_amount;
                                $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            } elseif ($o < $coupon_amount * 0.5 && $o1 > $purchasing_discount_money * 0.5) {
                                $many1 = $coupon_amount * 0.5 - $o;
                                if ($o1 < $purchasing_discount_money * 0.5 + $many1) {
                                    return ['code' => 300, 'msg' => "未达到使用门槛"];
                                }
                                $purchasing_discount_money = $purchasing_discount_money + $many1;
                                $coupon_amount             = $o;
                                $ManFullMinusList          = $o - $coupon_amount;
                                $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            } elseif ($o > $coupon_amount * 0.5 && $o1 > $purchasing_discount_money * 0.5) {
                                
                                $coupon_amount             = $coupon_amount * 0.5;
                                $purchasing_discount_money = $purchasing_discount_money * 0.5;
                                if ($ManFullMinusList == 0) {
                                    $coupon_amounts = $coupon_amount + $give_money;
                                } else {
                                    $coupon_amounts = $coupon_amount;
                                }
                                $ManFullMinusList = $o - $coupon_amounts;
                                $PrFullMinusList  = $o1 - $purchasing_discount_money;
                                
                            }
                        }
                        
                        $main_id = $list['id'];
                    } elseif (((isset($agent_amount) && $agent_amount != 0) && (isset($toPrice) && $toPrice == 0)) || $agentProductToMonry != 0) {
                        $o2 = bcsub($agent_amount,$daiZhiSho,2);
                       
                        if ($agentProductToMonry > 0) {
                             $o2 += bcsub($agentProductToMonry,$daiZhiShoChan, 2);
                        }
                         if ($manProductToMonry == 0) {
                         
                             $o2 =bcsub($o2,$zhuZhiShoChan, 2);
                        }
                        if ($list['coupon_type'] == 1) {
                            if ($o2 < ($list['coupon_limit'] / 100)) {
                                return ['code' => 300, 'msg' => "未达到使用门槛"];
                            }
                            $purchasing_discount_money = ($list['coupon_amount'] / 100);
                            $PrFullMinusList           = $o2 - $purchasing_discount_money;
                            
                        }
                        if ($list['coupon_type'] == 2) {
                            if ($PrFullMinusList == 0) {
                                $PrFullMinusList = $o2;
                            }
                            $purchasing_discount_money = $PrFullMinusList * (1 - ($list['coupon_discount'] / 100));
                        }
                        $purchasing_id = $list['id'];
                    } elseif ((isset($agent_amount) && $agent_amount == 0) && (isset($toPrice) && $toPrice != 0)) {
                        $o3 =bcsub($toPrice,$zhuZhiSho,2);
                      if ($productToMonry > 0) {
                              $o3 += bcsub(bcsub($productToMonry,$daiZhiShoChan,2),$zhuZhiShoChan,2);
                        }
                        if ($list['coupon_type'] == 1) {
                            if ($o3 < ($list['coupon_limit'] / 100)) {
                                return ['code' => 300, 'msg' => "未达到使用门槛"];
                            }
                            $coupon_amount    = ($list['coupon_amount'] / 100);
                            $ManFullMinusList = $o3 - $coupon_amount + $give_money;
                            
                            
                        }
                        if ($list['coupon_type'] == 2) {
                            if ($ManFullMinusList == 0) {
                                $ManFullMinusList = $o3;
                            }
                            $coupon_amount = $ManFullMinusList * (1 - ($list['coupon_discount'] / 100));
                        }
                        $main_id = $list['id'];
                    }
                    
                }
                if ((isset($agent_amount) && $agent_amount != 0) || $agentProductToMonry != 0) {
                    $o4=bcsub($agent_amount,$daiZhiSho,2);
                    
                        if ($agentProductToMonry > 0) {
                              $o4 += bcsub($agentProductToMonry,$daiZhiShoChan,2);
                        }
                        if ($manProductToMonry == 0) {
                            $o4 = bcsub($o4,$zhuZhiShoChan,2);
                        }
                    if ($list['coupon_use_type'] == 2) {
                        if ($o4 < ($list['coupon_limit'] / 100)) {
                            return ['code' => 300, 'msg' => "未达到使用门槛"];
                        }
                        if ($list['coupon_type'] == 1) {
                            $purchasing_discount_money = ($list['coupon_amount'] / 100);
                            $PrFullMinusList           = $o4 - $purchasing_discount_money;
                            
                        }
                        
                        if ($list['coupon_type'] == 2) {
                            if ($PrFullMinusList == 0) {
                                $PrFullMinusList = $o4;
                            }
                            $purchasing_discount_money = $PrFullMinusList * (1 - ($list['coupon_discount'] / 100));
                            $PrFullMinusList           = $o4 - $purchasing_discount_money;
                            
                        }
                        
                    }
                    $purchasing_id = $list['id'];
                }
                
                array_push($couponList, ['purchasing_discount_money' => $purchasing_discount_money, 'main_discount_money' => $coupon_amount, 'main_id' => empty($coupon_amount) ? 0 : $main_id, 'envelopes_id' => empty($envelopes) ? 0 : $envelopes['envelopes_id'], 'order_id' => $order_id, 'purchasing_id' => empty($purchasing_discount_money) ? 0 : $purchasing_id,]);
            };
         
            $purchasing_discount += array_sum(array_column($couponList, 'purchasing_discount_money'));
            $give_money          += array_sum(array_column($couponList, 'main_discount_money'));
            
        }
       
        $give_money          += $giveMainPrice;
        $purchasing_discount += $givePrice;
        if (!empty($result)) {
            if (!empty(array_column($result, 'coutMainMoenyDiscount'))) {
                $give_money += array_sum(array_column($result, 'coutMainMoenyDiscount'));
            }
            if (!empty(array_column($result, 'coutMoenyDiscount'))) {
                $purchasing_discount += array_sum(array_column($result, 'coutMoenyDiscount'));
            }
        }
        if (empty($order_setting)) {
            return ['code' => 300, 'msg' => "优惠.管理费初始化错误"];
        }
        
        if (($give_money - $coutMainMoenyDiscountMoney) != 0 && ($toPrice + $manProductToMonry + $giveMainPrice-$zhuZhiSho) == 0) {
            return ['code' => 300, 'msg' => "主合同优惠金额不能大于主合同清单总价的" . $order_setting["max_discount_rate"] . "%".'（报价中包含直售清单（店长固定提点清单），此类清单无法优惠，设置优惠金额时，请按照合同总价减去直售清单售价后的金额来设置）'];
        }
        if ($order_setting['max_discount_rate'] != 0 && ($toPrice != 0 || $manProductToMonry != 0 || $giveMainPrice != 0)) {
             if($manProductToMonry>0){
                $manProductToMonry=$manProductToMonry-$zhuZhiShoChan;
            }
             if($agentProductToMonry==0){
                   $manProductToMonry=$manProductToMonry-$daiZhiShoChan; 
                }
            if ((($toPrice + $manProductToMonry + $giveMainPrice-$zhuZhiSho) >0)  && ((string)(round(($give_money - $coutMainMoenyDiscountMoney) / ($toPrice + $manProductToMonry + $giveMainPrice-$zhuZhiSho), 3) * 100) > $order_setting['max_discount_rate'])) {
                return ['code' => 300, 'msg' => "主合同优惠金额不能大于主合同清单总价的" . $order_setting["max_discount_rate"] . "%".'（报价中包含直售清单（店长固定提点清单），此类清单无法优惠，设置优惠金额时，请按照合同总价减去直售清单售价后的金额来设置）'];
            }
        }
        //直售不算优惠 清单产品都不算
        if (($purchasing_discount - $coutMoenyDiscountMoney) != 0 && ($agent_amount + $agentProductToMonry + $givePrice-$daiZhiSho) == 0) {
            return ['code' => 300, 'msg' => "代购合同优惠金额不能大于代购合同清单总价的" . $order_setting["max_agent_discount_rate"] . "%".'（报价中包含直售清单（店长固定提点清单），此类清单无法优惠，设置优惠金额时，请按照合同总价减去直售清单售价后的金额来设置）1'];
        }
        if ($order_setting['max_agent_discount_rate'] != 0 && ($agent_amount != 0 || $agentProductToMonry != 0 || $givePrice != 0)) {
            if ($agentProductToMonry > 0) {
                $agentProductToMonry = $agentProductToMonry - $daiZhiShoChan;
            }
            if ($manProductToMonry == 0) {
                $agentProductToMonry = $agentProductToMonry - $zhuZhiShoChan;
            }
            if (($agent_amount + $agentProductToMonry + $givePrice - $daiZhiSho) > 0 && (string)(round(($purchasing_discount - $coutMoenyDiscountMoney) / ($agent_amount + $agentProductToMonry + $givePrice - $daiZhiSho), 3) * 100) > $order_setting['max_agent_discount_rate']) {
                return ['code' => 300, 'msg' => "代购合同优惠金额不能大于代购合同清单总价的" . $order_setting["max_agent_discount_rate"] . "%" . '（报价中包含直售清单（店长固定提点清单），此类清单无法优惠，设置优惠金额时，请按照合同总价减去直售清单售价后的金额来设置）'];
            }
        }

        foreach ($sys_config as $value) {
            if ($value['id'] == 0) {
                if ($toPrice + $manProductToMonry + $giveMainPrice >= $value['amount'] && $value['gong'] <= $gong) {
                    foreach ($value['select'] as $k1 => $l) {
                        $detailed=db('detailed')->where('detailed_id', $l['id'])->where('is_compose',1)->where('display', 1)->find();
                        if (!empty($detailed) && !in_array($l['id'], array_column($exist, 'product_id'))) {
                            return ['code' => 301, 'id' => $l['id'], 'is_required' => 1, 'title' => '主合同金额大于等于' . $value['amount'] . '且主合同工期大于等于' . $value['gong'] . '天时，' . '强关联必选【保洁清单】', 'msg' => '主合同金额大于等于' . $value['amount'] . '且主合同工期大于等于' . $value['gong'] . '天时，' . '强关联必选【保洁清单】', 'list' => $op];
                        }
                    }
                }
            }
        }
         
        if($agent_amount == 0 && $agentProductToMonry == 0 && $givePrice == 0 && ($purchasing_discount - $coutMoenyDiscountMoney) >0){
               return ['code' => 300, 'msg' => '非纯主材标品，代购不可增加优惠']; 
            }
        // if (!empty($resultListArray)) {
            
        //     foreach ($capitalList as $k => $item) {
        //         foreach ($resultListArray as $o) {
        //             if ($item['uniqueNumber'] == $o['uniqueNumber'] && $item['unique_status'] == 1) {
        //                 $capitalList[$k]['products_spec_price'] = $o['products_spec_price'];
        //             }
        //         }
        //     }
        // }
    
        return ['code' => 200, 'scheme_useListArray' => $scheme_useListArray, 'couponList' => $couponList, 'resultListArray' => $resultListArray, 'capitalList' => $capitalList, 'result' => $result, 'give_money' => $give_money, 'purchasing_discount' => $purchasing_discount, 'order_setting' => $order_setting];
    }
    
    /*
* 报价核检
* 根据清单匹配价格
*/
    public function inspection(array $companyJson, array $productJson, string $order_id, $common, $capital, $detailedOptionValue, $give_money, $purchasing_discount, $couponId, $productIds, $user_id, $order_setting, $project_title, $expense = 0, $purchasing_expense = 0) {
        $mainMaterials   = [];//套餐中时候存在主材
        $agencyMaterials = [];//套餐中时候存在代购主材
        $productOld      = [];//老产品
        $productNew      = [];//新产品
//套餐清单总价
        $totalPriceOfPackage = 0;
        $coutMainMoeny       = [];
        $capitalList         = [];
        $companyLists        = [];
        $productList         = [];
        $capitalListValue    = [];
        $productToMonry      = 0;
        $givePrice           = 0;
        $giveMainPrice       = 0;
        $toPrice             = 0;
        $agent_amount        = 0;
        
        $couponList = [];
        if ($companyJson) {
            if (!empty($companyJson)) {
                foreach ($companyJson as $ke => $value) {
                    $value['NewProducts']         = 0;
                    $value['sales_method']        = 0;
                    $value['products_spec_price'] = isset($value['productsSpecPrice']) ? $value['productsSpecPrice'] : 0;
                    $companyLists[]               = $value;
                }
                
            }
        }
        if (!empty($productJson)) {
            foreach ($productJson as $item) {
                if (!empty($item['list'])) {
                    foreach ($item['list'] as $k => $v) {
                        if (!empty($v['data'])) {
                            foreach ($v['data'] as $ke => $value) {
                                $value['categoryName']        = $v['title'];
                                $value['products_spec_price'] = $v['productsSpecPrice'];
                                $value['initialSalesVolume']  = isset($item['initialSalesVolume']) ? $item['initialSalesVolume'] : 0;
                                $value['startingVolume']      = isset($item['startingVolume']) ? $item['startingVolume'] : 0;
                                $value['sales_method']        = isset($item['sales_method']) ? $item['sales_method'] : 1;
                                $value['products_unit_price'] = isset($item['productsUnitPrice']) ? $item['productsUnitPrice'] : 0;
                                $value['NewProducts']         = 1;
                                $value['fang']                = $value['square'];
                                $value['product_id']          = $value['projectId'];
                                $value['unit']                = $value['company'];
                                $value['products']            = 1;
                                $value['type']                = 1;
                                $value['prices']              = $value['projectMoney'];
                                $value['sectionTitle']        = isset($value['sectionTitle']) ? $value['sectionTitle'] : '';
                                $productList[]                = $value;
                            }
                        }
                        
                    }
                }
                
            }
        }
        $op = array_merge($companyLists, $productList);
        if (!empty($op)) {
            $mergeArray = [];//合并
            foreach ($op as $k => $l) {
                $op[$k]['newFang'] = 0;
                if ($l['isMerge']) {
                    $pf = json_decode(explode('|', $l['mergeTag'])[1], true);
                    sort($pf);
                    $l['mergeTag']      = explode('|', $l['mergeTag'])[0] . '|' . json_encode($pf);
                    $mergeArray[]       = $l;
                    $op[$k]['mergeTag'] = $l['mergeTag'];
                }
            }
            if (!empty($mergeArray)) {
                $result = array_reduce($mergeArray, function ($temp, $item) {
                    isset($temp[$item['mergeTag']]) ? $temp[$item['mergeTag']]['fang'] += $item['fang'] : $temp[$item['mergeTag']] = $item;
                    return $temp;
                }, []);
                foreach ($result as $l) {
                    foreach ($op as $k => $pl) {
                        if ($pl['isMerge'] && ($l['mergeTag'] == $pl['mergeTag'])) {
                            $op[$k]['newFang'] = $l['fang'];
                        }
                    }
                }
            }
            $y = $op;
            foreach ($op as $ke => $v) {
                $ValueList = $v['specsList'];
                if ($v['types'] == 4) {
                    $ValueId      = array_column($ValueList, 'option_value_id');
                    $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $v['product_id'], array_merge(array_unique($ValueId)));
                    
                    if (!$CapitalPrice['code']) {
                        return ['code' => 300, 'msg' => $CapitalPrice['msg']];
                    }
                    if ($v['isMerge'] && $v['newFang'] != 0) {
                        $fang = $v['newFang'];
                    } else {
                        $fang = $v['fang'];
                    }
                    $fangs = -1;
                    if (!empty($CapitalPrice['data']['small_order_fee']) && ($v['products'] == 0 || ($v['products'] == 1 && $v['required'] == 2 && $v['isProductChoose'])) && $v['smallOrderFeeType'] == 1) {
                        $fangs = $fang;
                    }
                    $v['unique_status']               = 0;
                    $CapitalPriceSection              = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $fang, $v['unit'], $CapitalPrice['data']['small_order_fee'], $fangs);
                    $capitalMap['labor_cost_price']   = $CapitalPriceSection[0];
                    $capitalMap['sumMast']            = $CapitalPriceSection[2];
                    $capitalMap['smallOrderFeePrice'] = $CapitalPriceSection[5];
                    $capitalMap['base_cost']          = 0;
                    if ($v['agency'] == 1) {
                        $capitalMap['labor_cost_price'] = $CapitalPrice['data']['sumMast'] * $fang;
                        $capitalMap['base_cost']        = $CapitalPrice['data']['base_cost'];
                        $capitalMap['sumMast']          = $CapitalPrice['data']['sumMast'];
                    }
                    
                    $capitalMap['toPrice']           = $CapitalPriceSection[3] * $v['fang'];
                    $capitalMap['sum']               = $CapitalPriceSection[3];
                    $capitalMap['mast_rule']         = $CapitalPriceSection[4];
                    $capitalMap['is_product_choose'] = 1;
                    if (isset($v['products']) && $v['products'] == 1 && $v['NewProducts'] == 0) {
                        $v['unique_status']    = 0;
                        $capitalMap['toPrice'] = $v['allMoney'];
                        $totalPriceOfPackage   += $capitalMap['toPrice'];
                        $productOld[]          = ['toPrice' => $capitalMap['toPrice'], 'agency' => $v['agency'], 'sales_method' => $v['sales_method'], 'products_id' => $v['products_id'], 'schemeIds' => $v['schemeIds'], 'uniqueNumber' => $v['uniqueNumber'], 'isGiveUpProducts' => $v['isGiveUpProducts'], 'productType' => 1,];
                        $capitalMap['sum']     = $v['prices'];
                        if ($v['agency'] == 0) {
                            $mainMaterials[] = $v;
                        }
                        if ($v['agency'] == 1) {
                            $agencyMaterials[] = $v;
                        }
                        $plan_id = db('scheme_project', config('database.zong'))->Join('scheme_master', 'scheme_master.plan_id=scheme_project.plan_id', 'left')->where('scheme_project.plan_id', $v['schemeIds'])->select();
                        foreach ($plan_id as $item) {
                            if ($item['settlement_method'] == 2 && $item['projectId'] == $v['product_id']) {
                                $capitalMap['labor_cost_price'] = $item['fixed_price'];
                                $capitalMap['sumMast']          = round($item['fixed_price'] / $v['fang'], 2);
                            }
                            
                        }
                        
                        $capitalMap['mast_rule'] = '';
                    } elseif (isset($v['products']) && $v['products'] == 1 && $v['NewProducts'] == 1) {
                        if ($v['required'] == 1) {
                            $v['unique_status']    = 1;
                            $capitalMap['toPrice'] = $v['allMoney'];
                            $totalPriceOfPackage   += $capitalMap['toPrice'];
                            if ($v['agency'] == 0) {
                                $mainMaterials[] = $v;
                            }
                            if ($v['agency'] == 1) {
                                $agencyMaterials[] = $v;
                            }
                            $capitalMap['sum']       = $v['projectMoney'];
                            $capitalMap['mast_rule'] = '';
                            $productNew []           = ['toPrice' => $capitalMap['toPrice'], 'agency' => $v['agency'], 'products_id' => $v['products_id'], 'schemeIds' => $v['schemeIds'], 'sales_method' => $v['sales_method'], 'uniqueNumber' => $v['uniqueNumber'], 'sales_volume' => $v['initialSalesVolume'], 'startingVolume' => $v['startingVolume'], 'products_unit_price' => $v['products_unit_price'], 'isGiveUpProducts' => 0, 'productType' => 2,];
                        }
                        if ($v['required'] == 2 && $v['isProductChoose']) {
                            $v['unique_status'] = 0;
                            if ($v['agency'] == 1 && $v['giveType'] == 0) {
                                $agent_amount += $capitalMap['toPrice'];
                            } elseif ($v['agency'] == 0 && $v['giveType'] == 0) {
                                $toPrice += $capitalMap['toPrice'];
                            }
                            
                        }
                    }
                    if ($v['giveType'] == 2 && $capitalMap['is_product_choose'] == 1) {
                        if ($v['agency'] == 1) {
                            $givePrice += $capitalMap['toPrice'];
                        } else {
                            $giveMainPrice += $capitalMap['toPrice'];
                        }
                    }
                    if ($v['agency'] == 0 && $v['products'] == 0 && $v['giveType'] == 0) {
                        $toPrice += round($capitalMap['toPrice'], 2);
                    }
                    if ($v['agency'] == 1 && $v['products'] == 0 && $v['giveType'] == 0) {
                        $agent_amount += round($capitalMap['toPrice'], 2);
                    }
                }
                $option_value_id                     = array_column($v['specsList'], 'option_value_id');
                $specsList                           = \db('detailed_option_value_material')->field("group_concat(detailed_option_value_material.invcode) as invcode,
                  CONCAT('[', GROUP_CONCAT(JSON_OBJECT('invcode',detailed_option_value_material.invcode,'option_value_id',detailed_option_value_material.option_value_id,'recommended_quantity',detailed_option_value_material.recommended_quantity,'sum',0) SEPARATOR ','), ']') as  content")->whereIn('detailed_option_value_material.option_value_id', $option_value_id)->find();
                $capitalList[$ke]['invcode']         = empty($specsList) ? '' : $specsList['invcode'];//三
                $capitalList[$ke]['content']         = empty($specsList) ? '' : $specsList['content'];//三
                $capitalList[$ke]['envelopes_id']    = 0;//三
                $capitalList[$ke]['type']            = 0;//三
                $capitalList[$ke]['project_title']   = $project_title;
                $capitalList[$ke]['agency']          = $v['agency'];
                $capitalList[$ke]['order_fee']       = $order_setting['order_fee'];
                $capitalList[$ke]['square']          = 0;
                $capitalList[$ke]['groupss']          = $CapitalPrice['data']['group'];
                $capitalList[$ke]['material_ratio']          =  $CapitalPrice['data']['material_ratio'];
                $capitalList[$ke]['base_cost']       = 0;
                $capitalList[$ke]['agent_price']     = 0;
                $capitalList[$ke]['daiLaborCost']    = 0;//三
                $capitalList[$ke]['daiMaterialCost'] = 0;//三
                $capitalList[$ke]['uniqueNumber']    = isset($v['uniqueNumber']) ? $v['uniqueNumber'] : 0;//三
                $capitalList[$ke]['unique_status']   = $v['unique_status'];
                $capitalList[$ke]['square']          = 0;
                $capitalList[$ke]['main_price']      = 0;
                $capitalList[$ke]['zhuLaborCost']    = 0;//三
                if (($v['agency'] == 1 && $v['products'] != 1) || ($v['products'] == 1 && $v['unique_status'] && $v['agency'] == 1)) {
                    $capitalList[$ke]['square']          = $v['fang'];
                    $capitalList[$ke]['agent_price']     = $capitalMap['toPrice'] + $capitalMap['smallOrderFeePrice'] + $capitalMap['smallOrderFeePrice'];
                    $capitalList[$ke]['daiLaborCost']    = round($capitalMap['sumMast'] * $v['fang'], 2);//三
                    $capitalList[$ke]['daiMaterialCost'] = round($capitalMap['base_cost'] * $v['fang'], 2);//三
                    
                }
                if (($v['agency'] == 0 && $v['products'] != 1) || ($v['products'] == 1 && $v['unique_status'] && $v['agency'] == 0)) {
                    $capitalList[$ke]['square']       = $v['fang'];
                    $capitalList[$ke]['main_price']   = $capitalMap['toPrice'] + $capitalMap['smallOrderFeePrice'];
                    $capitalList[$ke]['zhuLaborCost'] = round($capitalMap['sumMast'] * $v['fang'], 2);//三
                }
            }
        }
        //套餐
        $result = array();
        if (!empty($productIds)) {
            if (!empty($productOld) && !empty($productNew)) {
                $coutMainMoeny = array_merge($productOld, $productNew);
            } elseif (!empty($productOld) && empty($productNew)) {
                $coutMainMoeny = $productOld;
            } elseif (empty($productOld) && !empty($productNew)) {
                $coutMainMoeny = $productNew;
            }
            
            if (!empty($coutMainMoeny)) {
                $title = array_unique(array_column($coutMainMoeny, 'uniqueNumber'));
                foreach ($title as $key => $info) {
                    $money    = 0;
                    $allMoney = [];
                    foreach ($coutMainMoeny as $item) {
                        if ($info == $item['uniqueNumber']) {
                            $result[$key]['products_id']         = $item['products_id'];
                            $result[$key]['schemeIds']           = $item['schemeIds'];
                            $result[$key]['sales_method']        = $item['sales_method'];
                            $result[$key]['sales_volume']        = isset($item['sales_volume']) ? $item['sales_volume'] : 0;
                            $result[$key]['startingVolume']      = isset($item['startingVolume']) ? $item['startingVolume'] : 0;
                            $result[$key]['products_unit_price'] = isset($item['products_unit_price']) ? $item['products_unit_price'] : 0;
                            $result[$key]['productType']         = $item['productType'];
                            $money                               += $item['toPrice'];
                            $allMoney[]                          = ['toPrice' => $item['toPrice'], 'agency' => $item['agency'], 'isGiveUpProducts' => $item['isGiveUpProducts'],];
                        }
                    }
                    if ($result[$key]['productType'] == 1) {
                        $products_spec                       = db('products_spec', config('database.zong'))->where('products_id', $result[$key]['products_id'])->join('products', 'products.id=products_spec.products_id', 'left')->join('unit', 'products.products_unit=unit.id', 'left')->where('scheme_id', $result[$key]['schemeIds'])->field('products_spec.*,products.*,unit.title as unitTitle')->find();
                        $productToMonry                      += round($products_spec['products_spec_price'] / 100, 2);
                        $beLeftOver                          = round($money, 2) - round($products_spec['products_spec_price'] / 100, 2);
                        $result[$key]['products_spec_price'] = round($products_spec['products_spec_price'] / 100, 2);
                        $title                               = $products_spec['products_title'] . '-' . $products_spec['products_spec_title'];
                        $products_spec_price                 = round($products_spec['products_spec_price'] / 100, 2);
                        $products_spec_title                 = $products_spec['products_spec_title'];
                        $products_unit                       = $products_spec['unitTitle'];
                    } elseif ($result[$key]['productType'] == 2) {
                        $products_spec = db('products_v2_spec', config('database.zong'))->field('products.*,products_v2_spec.*,products.id as ids,unit.title as unitTitle,products.sales_method,products.products_unit_price')->join('products_v2 products', 'products.id=products_v2_spec.products_id', 'left')->join('unit', 'products.products_unit=unit.id', 'left')->where('products_v2_spec.products_id', $result[$key]['products_id'])->where('products_v2_spec.is_required_module', 1)->select();
                        foreach ($products_spec as $lp) {
                            if ($lp['sales_method'] == 2) {
                                $productToMonry                      += round($lp['products_unit_price'] * $result[$key]['sales_volume'], 2);
                                $products_spec_price                 = round($lp['products_unit_price'] * $result[$key]['sales_volume'], 2);
                                $result[$key]['products_unit_price'] = $lp['products_unit_price'];
                            } else {
                                $productToMonry      += round($lp['products_spec_price'], 2);
                                $products_spec_price = round($lp['products_spec_price'], 2);
                            }
                        }
//                        $products_spec_price = round(array_sum(array_column($products_spec, 'products_spec_price')), 2);
                        $beLeftOver          = round($money - $products_spec_price, 2);
                        $title               = $products_spec[0]['products_title'];
                        $products_spec_title = "";
                        $products_unit       = $products_spec[0]['unitTitle'];
                    };
                    $coutMainMoenyDiscountMoney  = 0;
                    $coutMoenyDiscountMoney      = 0;
                    $products_main_expense       = 0;
                    $products_purchasing_expense = 0;
                    if ($beLeftOver >= 0) {
                        $last_man_datas = array_column($allMoney, 'toPrice');
                        array_multisort($last_man_datas, SORT_ASC, $allMoney);
                        $Proportion = 0;
                        foreach ($allMoney as $k => $m) {
                            if ($k != count($allMoney) - 1) {
//                                $Proportion                 += bcdiv($m['toPrice'], $money, 2);
                                $allMoney[$k]['proportion'] = bcdiv($m['toPrice'], $money, 2);
                            }
                            if ($m['agency'] == 1 && $m['isGiveUpProducts'] == 0) {
                                $products_purchasing_expense += $m['toPrice'];
                            }
                            if ($m['agency'] == 0 && $m['isGiveUpProducts'] == 0) {
                                $products_main_expense += $m['toPrice'];
                            }
                            
                        }
                        foreach ($allMoney as $k => $m) {
                            if ($k == count($allMoney) - 1) {
                                $allMoney[$k]['proportionAmount'] = bcsub($beLeftOver, $Proportion, 3);
                            } else {
                                $allMoney[$k]['proportionAmount'] = bcmul($beLeftOver, $m['proportion'], 2);
                                $Proportion                       += $allMoney[$k]['proportionAmount'];
                            }
                            
                        }
                        foreach ($allMoney as $k => $j) {
                            if ($j['agency'] == 1) {
                                $coutMoenyDiscountMoney += $j['proportionAmount'];
                            }
                            if ($j['agency'] == 0) {
                                $coutMainMoenyDiscountMoney += $j['proportionAmount'];
                            }
                        }
                    } else {
                        return ['code' => 300, 'msg' => "产品配置出现问题，请截图联系供应链【戚君丞】【产品" . $result[$key]['products_id'] . "】"];
                    }
                    $result[$key]['money']      = $money;
                    $result[$key]['beLeftOver'] = $beLeftOver;
//                    $result[$key]['startingVolume']                  = $result[$key]['startingVolume'] ;
                    $result[$key]['coutMainMoenyDiscount']       = $coutMainMoenyDiscountMoney;
                    $result[$key]['coutMoenyDiscount']           = $coutMoenyDiscountMoney;
                    $result[$key]['products_main_expense']       = round(($products_main_expense * $order_setting['max_expense_rate']) / 100, 2);
                    $result[$key]['products_purchasing_expense'] = round(($products_purchasing_expense * $order_setting['max_agent_expense_rate']) / 100, 2);
                    $result[$key]['uniqueNumber']                = $info;
                    $result[$key]['title']                       = $title;
                    $result[$key]['products_spec_price']         = $products_spec_price;
                    $result[$key]['products_spec_title']         = $products_spec_title;
                    $result[$key]['products_unit']               = $products_unit;
                }
                
                $result = array_values($result);
                
            }
            
        }
        $coutMoenyDiscountMoney     = 0;
        $coutMainMoenyDiscountMoney = 0;
        $resultListArray            = [];
        $scheme_useListArray        = [];
        $manProductToMonry          = 0;
        $agentProductToMonry        = 0;

//优惠券
        if (!empty($couponId) && trim($couponId) != 'null') {
            $exp       = new \think\db\Expression('field(coupon.coupon_type,1,2)');
            $couponId  = json_decode($couponId, true);
            $couponId  = implode(array_column($couponId, 'id'), ',');
            $coupon    = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->whereIn('coupon_user.id', $couponId)->order($exp)->select();
            $fullMinus = [];
            $discount  = [];
            foreach ($coupon as $item) {
                if ($item['coupon_type'] == 1) {
                    $fullMinus[] = $item;
                }
                if ($item['coupon_type'] == 2) {
                    $discount[] = $item;
                }
            }
            $coupon_use_type = array_column($fullMinus, 'coupon_use_type');
            array_multisort($coupon_use_type, SORT_ASC, $fullMinus);
            $discountcoupon_use_type = array_column($discount, 'coupon_use_type');
            array_multisort($discountcoupon_use_type, SORT_ASC, $discount);
            $coupon           = array_merge($fullMinus, $discount);
            $ManFullMinusList = 0;
            $PrFullMinusList  = 0;
            foreach ($coupon as $k => $list) {
                $coupon_amount             = 0;
                $purchasing_id             = 0;
                $purchasing_discount_money = 0;
                $main_id                   = 0;
                if ($list['coupon_use_type'] == 1) {
                    if ((isset($toPrice) && $toPrice != 0) || $manProductToMonry != 0) {
                        $o = $toPrice + $manProductToMonry;
                        if ($list['coupon_type'] == 1) {
                            $coupon_amount    = ($list['coupon_amount'] / 100);
                            $ManFullMinusList = $o - $coupon_amount - $give_money;
                        } elseif ($list['coupon_type'] == 2) {
                            if ($ManFullMinusList == 0) {
                                $ManFullMinusList = $o - $give_money;
                            }
                            $coupon_amount    = $ManFullMinusList * (1 - ($list['coupon_discount'] / 100));
                            $ManFullMinusList = $o - $coupon_amount - $give_money;
                        }
                        $main_id = $list['id'];
                    }
                }
                if ($list['coupon_use_type'] == 3) {
                    if ((isset($agent_amount) && $agent_amount != 0) && (isset($toPrice) && $toPrice != 0)) {
                        $o1 = round($agent_amount, 2);
                        $o  = round($toPrice, 2);
                        if ($list['coupon_type'] == 1) {
                            $coupon_amount             = ($list['coupon_amount'] / 100);
                            $purchasing_discount_money = ($list['coupon_amount'] / 100);
                        } elseif ($list['coupon_type'] == 2) {
                            if ($ManFullMinusList == 0) {
                                $ManFullMinusList = $o - $give_money;
                            }
                            if ($PrFullMinusList == 0) {
                                $PrFullMinusList = $o1;
                            }
                            $coupon_amount             = $ManFullMinusList * (1 - ($list['coupon_discount'] / 100));
                            $purchasing_discount_money = $PrFullMinusList * (1 - ($list['coupon_discount'] / 100));
                        }
                        if ($list['coupon_type'] == 1) {
                            if ($o < $coupon_amount * 0.5 && $o1 < $purchasing_discount_money * 0.5) {
                            
                            } elseif ($o > $coupon_amount * 0.5 && $o1 < $purchasing_discount_money * 0.5) {
                                
                                $many                      = $purchasing_discount_money * 0.5 - $o1;
                                $coupon_amount             = $coupon_amount + $many;
                                $purchasing_discount_money = $o1;
                                $ManFullMinusList          = $o - $coupon_amount;
                                $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            } elseif ($o < $coupon_amount * 0.5 && $o1 > $purchasing_discount_money * 0.5) {
                                $many1                     = $coupon_amount * 0.5 - $o;
                                $purchasing_discount_money = $purchasing_discount_money + $many1;
                                $coupon_amount             = $o;
                                $ManFullMinusList          = $o - $coupon_amount;
                                $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            } elseif ($o > $coupon_amount * 0.5 && $o1 > $purchasing_discount_money * 0.5) {
                                
                                $coupon_amount             = $coupon_amount * 0.5;
                                $purchasing_discount_money = $purchasing_discount_money * 0.5;
                                if ($ManFullMinusList == 0) {
                                    $coupon_amounts = $coupon_amount + $give_money;
                                } else {
                                    $coupon_amounts = $coupon_amount;
                                }
                                $ManFullMinusList = $o - $coupon_amounts;
                                $PrFullMinusList  = $o1 - $purchasing_discount_money;
                                
                            }
                        }
                        
                        $main_id = $list['id'];
                    } elseif (((isset($agent_amount) && $agent_amount != 0) && (isset($toPrice) && $toPrice == 0)) || $agentProductToMonry != 0) {
                        $o1 = round($agent_amount + $agentProductToMonry, 2);
                        if ($list['coupon_type'] == 1) {
                            $purchasing_discount_money = ($list['coupon_amount'] / 100);
                            $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            
                        }
                        if ($list['coupon_type'] == 2) {
                            if ($PrFullMinusList == 0) {
                                $PrFullMinusList = $o1;
                            }
                            $purchasing_discount_money = $PrFullMinusList * (1 - ($list['coupon_discount'] / 100));
                        }
                        $purchasing_id = $list['id'];
                    } elseif ((isset($agent_amount) && $agent_amount == 0) && (isset($toPrice) && $toPrice != 0)) {
                        $o = round($toPrice, 2) + $productToMonry;
                        if ($list['coupon_type'] == 1) {
                            $coupon_amount    = ($list['coupon_amount'] / 100);
                            $ManFullMinusList = $o - $coupon_amount + $give_money;
                        }
                        if ($list['coupon_type'] == 2) {
                            if ($ManFullMinusList == 0) {
                                $ManFullMinusList = $o;
                            }
                            $coupon_amount = $ManFullMinusList * (1 - ($list['coupon_discount'] / 100));
                        }
                        $main_id = $list['id'];
                    }
                    
                }
                if ((isset($agent_amount) && $agent_amount != 0) || $agentProductToMonry != 0) {
                    $o1 = round($agent_amount + $agentProductToMonry, 2);
                    if ($list['coupon_use_type'] == 2) {
                        if ($list['coupon_type'] == 1) {
                            $purchasing_discount_money = ($list['coupon_amount'] / 100);
                            $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            
                        }
                        
                        if ($list['coupon_type'] == 2) {
                            if ($PrFullMinusList == 0) {
                                $PrFullMinusList = $o1;
                            }
                            $purchasing_discount_money = $PrFullMinusList * (1 - ($list['coupon_discount'] / 100));
                            $PrFullMinusList           = $o1 - $purchasing_discount_money;
                            
                        }
                        
                    }
                    $purchasing_id = $list['id'];
                }
                
                array_push($couponList, ['purchasing_discount_money' => $purchasing_discount_money, 'main_discount_money' => $coupon_amount, 'main_id' => empty($coupon_amount) ? 0 : $main_id, 'envelopes_id' => empty($envelopes) ? 0 : $envelopes['envelopes_id'], 'order_id' => $order_id, 'purchasing_id' => empty($purchasing_discount_money) ? 0 : $purchasing_id,]);
            };
            $purchasing_discount += array_sum(array_column($couponList, 'purchasing_discount_money'));
            $give_money          += array_sum(array_column($couponList, 'main_discount_money'));
            
        }
        $give_money          += $giveMainPrice;
        $purchasing_discount += $givePrice;
        if (!empty($result)) {
            if (!empty(array_column($result, 'coutMainMoenyDiscount'))) {
                $give_money += array_sum(array_column($result, 'coutMainMoenyDiscount'));
            }
            if (!empty(array_column($result, 'coutMoenyDiscount'))) {
                $purchasing_discount += array_sum(array_column($result, 'coutMoenyDiscount'));
            }
        }
        foreach ($capitalList as $k => $item) {
            $capitalList[$k]['give_money']          = $give_money;
            $capitalList[$k]['expense']             = $expense;
            $capitalList[$k]['purchasing_discount'] = $purchasing_discount;
            $capitalList[$k]['purchasing_expense']  = $purchasing_expense;
            $capitalList[$k]['created_time']        = time();
        }
        return ['code' => 200, 'capitalList' => $capitalList];
    }
    
}
